
import 'package:banyou_app/app/config/colors.dart';
import 'package:banyou_app/app/widget/app_bar_widget.dart';
import 'package:banyou_app/app/widget/login_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../controllers/web_controller.dart';
import 'package:webview_flutter/webview_flutter.dart' as webv;
import 'package:webview_flutter/webview_flutter.dart';

class WebView extends GetView<WebController> {
  @override
  Widget build(BuildContext context) {
    return Obx(
      () => Scaffold(
          appBar: getAppBarWidget(),
          body: SafeArea(
            child: Stack(
              children: [
                Positioned.fill(child: web()),
                Obx(() => controller.isbase.value
                    ? Positioned(
                        top: 44,
                        left: 0,
                        right: 0,
                        height: 60,
                        child: Obx(() => (controller.showAddress.value)
                            ? addressWidget()
                            : Container()),
                      )
                    : Container())
              ],
            ),
          )),
    );
  }

  Widget addressWidget() {
    return Container(
      margin: EdgeInsets.only(left: 16, right: 16, top: 15),
      padding: EdgeInsets.symmetric(horizontal: 16),
      width: 1.sw,
      height: 45,
      decoration: BoxDecoration(
          color: Color(0xFF35363F),
          borderRadius: BorderRadius.all(Radius.circular(6)),
          border: Border.all(color: Color(0xFF35363F))),
      child: Container(
        child: Row(
          children: [
            Text('开启位置权限',
                style: TextStyle(
                    fontSize: 15.sp,
                    color: ColorConfig.app_main,
                    fontWeight: FontWeight.w400)),
            Spacer(),
            Container(
              width: 65.w,
              height: 30,
              child: LoginButton("开启", enable: true, onPressed: () {
                controller.openSet();
              }),
            )
          ],
        ),
      ),
    );
  }

  getAppBarWidget() {
    return AppBarWidget(
        showLeading: true,
        leadingCallback: () async {
          if (controller.webViewController != null) {
            bool a = await controller.webViewController!.canGoBack();
            if (a) {
              controller.webViewController!.goBack();
            } else {
              Get.back();
            }
          } else {
            Get.back();
          }
        },
        titleStr: controller.title.value);
  }

  web() {
    return Obx(() => controller.url.value.length > 0
        ? webv.WebView(
            initialUrl: controller.url.value, //需要打开的url
            //是否支持js 默认是不支持的，
            javascriptMode: webv.JavascriptMode.unrestricted,
            gestureNavigationEnabled: true,
            //加载js方法到页面内，js通过此来调用flutter的方法
            javascriptChannels: _loadJavascriptChannel(),
            navigationDelegate: (NavigationRequest request) {
              if (request.url.startsWith('servicef')) {
                // Bridge.preventUrl(request.url, _controller);
                Uri service = Uri.parse(request.url);
                Map q = service.queryParameters;
                if (q.isNotEmpty && q.containsKey('url')) {
                  controller.launchURL(Uri.parse(q['url']));
                }
                return NavigationDecision.prevent;
              }

              return NavigationDecision.navigate;
            },

            onWebViewCreated: (web) {
              controller.webViewController = web;
            },
            onPageFinished: (url) async {
              String title = await controller.webViewController!
                  .runJavascriptReturningResult('document.title');
              print('title=======' + title);
              if (title != '') {
                controller.title.value = title;
              }
            },
          )
        : Container());
  }

  Set<JavascriptChannel> _loadJavascriptChannel() {
    final Set<JavascriptChannel> channels = Set<JavascriptChannel>();
    JavascriptChannel startFunction = JavascriptChannel(
        name: 'startFunction',
        onMessageReceived: (JavascriptMessage message) {
          // _getTitle();

          controller.messageHandle(message);
          // print(jsonDecode(message.message));
        });
    // JavascriptChannel h5JumpNative = JavascriptChannel(
    //     name: 'h5JumpNative',
    //     onMessageReceived: (JavascriptMessage message) {
    //       print('获取到方法');
    //       print(message.message);
    //     });
    // JavascriptChannel appJump = JavascriptChannel(
    //     name: 'appJump',
    //     onMessageReceived: (JavascriptMessage message) {
    //       print('获取到方法');
    //       print(message.message);
    //     });

    channels.addAll([
      startFunction,
    ]);
    return channels;
  }
}
